import 'package:flutter/material.dart';
import 'package:ichinesereader/models/school/SchoolStaticsData.dart';
import 'package:ichinesereader/models/report/chartData.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/charts/splineAreaChart.dart';
import 'package:get/get.dart';

class ReadBooksWidget extends StatelessWidget {
  ReadBooksWidget(
      {Key? key, required this.datamap, required this.isYear, this.month})
      : super(key: key);
  final Map<String, DataMap> datamap;
  final bool isYear;
  final int? month;

  List<List<SplineAreaChartData>> paddingData(
      List<List<SplineAreaChartData>> data) {
    if (data[0].length < 12) {
      if (data[0][0].month! > 1) {
        for (int i = data[0][0].month! - 1; i >= 1; i--) {
          data[0].insert(0, new SplineAreaChartData(data[0][0].year, i, 0));
        }
      }
    }
    if (data.length > 1) {
      var element = data[data.length - 1];
      if (element.length < 12) {
        if (element[element.length - 1].month! < 12) {
          for (int i = element[element.length - 1].month! + 1; i <= 12; i++) {
            element.add(new SplineAreaChartData(element[0].year, i, 0));
          }
        }
      }
    }
    return data;
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build ReadBooksWidget');

    Map<int, List<SplineAreaChartData>> totalReadBooksData = {};
    List<List<SplineAreaChartData>> usedReadBooksData = [];
    datamap.forEach((key, value) {
      if (isYear) {
        var month = int.parse(key.split("/")[0]);
        var year = int.parse(key.split("/")[1]);

        if (totalReadBooksData[year] != null) {
          totalReadBooksData[year]!
              .add(new SplineAreaChartData(year, month, value.readBooks!));
        } else {
          totalReadBooksData[year] = [
            new SplineAreaChartData(year, month, value.readBooks!)
          ];
        }
      } else {
        var m = int.parse(key.split("/")[0]);
        var date = int.parse(key.split("/")[1]);
        var year = int.parse(key.split("/")[2]);

        if (m == month) {
          if (totalReadBooksData[year] != null) {
            totalReadBooksData[year]!
                .add(new SplineAreaChartData(year, date, value.readBooks!));
          } else {
            totalReadBooksData[year] = [
              new SplineAreaChartData(year, date, value.readBooks!)
            ];
          }
        }
      }
    });

    totalReadBooksData.forEach((key, value) {
      usedReadBooksData.add(value);
    });
    if (isYear) {
      paddingData(usedReadBooksData);
    }

    return SplineAreaChart(
      title: "Total Read Books".tr,
      splineAreaChartData: usedReadBooksData,
      axisTitle: "Books",
      isYear: isYear,
    );
  }
}
